#include "XpmDocControl.h"
#include "dal/DocAccess.h"

namespace xpm {

	XpmDocControl::~XpmDocControl() {
		if(_access) {
			delete _access;
			_access = 0;
		}
	}
	int XpmDocControl::OpenDoc(string filename) {
		_doc.Clear();
		_access->SetFilename(filename.c_str());
		return _access->Load(_doc);
	}
	int XpmDocControl::OpenSigns(string filename, string signs) {
		if(_access) {
			_doc.Clear();
			_doc.setLang("en");
			_access->SetFilename(filename.c_str());
			return _access->Load(_doc, signs);
		}else
			return -1;

	}
	int XpmDocControl::SaveDoc(string filename, string syntax) {
		if(_access) {
			_access->SetFilename(filename.c_str());
			return _access->Save(_doc, syntax);
		}else
			return -1;
	}
	void XpmDocControl::Clear() {
		_doc.Clear();
	}
	// parse source to content and model
	string XpmDocControl::ParseSource(string source) {
		// get the syntax
		std::size_t pos = source.find("\"_lang");
		string content = source;
		if ( pos != string::npos ) {
			content = source.substr(0, pos) ;
			std::size_t spos = content.find_last_of("{")-1;
			content = content.substr(0, spos);
		}
		// get the model signs
		if ( pos != string::npos ) {
			string signs = pos != string::npos ? "{" + source.substr(pos, source.size()-pos-1) + "}": "" ;
			cout << "signs:" << signs << endl;
			_signs = signs;
			//parse signs to model
		}
		return content;
	}

	int XpmDocControl::LoadModel() {
		if(_signs.size() > 0) {
			_doc.Clear();
			_doc.setLang("en"); // default value
			return _access->Load(_doc, _signs);
		}
		return false;
	}

	string XpmDocControl::WriteTarget(string content) {
		return _access->WriteTarget(_doc, content);
	}
}